/*
条件变量应用实例
实现两个线程同步
首先执行线程1 操作后再执行线程2的功能
*/

#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

//定义一个锁 一个条件变量
pthread_mutex_t mutex;
pthread_cond_t cond;

void* func1(void* arg)
{
    int* a = static_cast<int*>(arg);
    
    while (true)
    {
        cout << "this is func1, data = " << *a << endl;
        *a += 1;
        pthread_cond_signal(&cond); 
        sleep(1);
    }
    
}
void* func2(void* arg)
{
    int* a = static_cast<int*>(arg);
    while (true)
    {
        pthread_cond_wait(&cond, &mutex);
        cout << "this is func2, data = " << *a << endl;
        *a += 1;
    }
}

int main()
{
    //init cond and mutex
    pthread_cond_init(&cond, NULL);
    pthread_mutex_init(&mutex, NULL);
    
    //创建两个线程 线程1 执行完成后 才能执行线程2中相应的一些操作
    pthread_t pid1, pid2;
    int* data = new int(0);

    pthread_create(&pid1, NULL, func1, data);
    pthread_create(&pid2, NULL, func2, data);

    pthread_join(pid1, NULL);
    pthread_join(pid2, NULL);

    pthread_mutex_destroy(&mutex);//销毁互斥锁
	pthread_cond_destroy(&cond);//销毁条件变量

    return 0;
}